import React, { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  message,
  Space,
  Popconfirm,
  Select,
} from "antd";
import { reqUserList } from "@/api/user";

const { Option } = Select;
interface User {
  uid: string;
  username: string;
  name: string;
  phone: number;
  isVIP: string;
}

const UserManagementPage: React.FC = () => {
  const [data, setData] = useState<User[]>([]); //数据源
  const [visible, setVisible] = useState(false); //是否可见
  const [form] = Form.useForm(); //表单里的值
  const [editingKey, setEditingKey] = useState(""); //编辑或是新增
  const [params, setParams] = useState({
    pageNum: 1,
    pageSize: 10,
    condition: {
      username: "",
      isVIP: "",
    },
  }); //请求值

  const columns = [
    {
      title: "用户昵称",
      dataIndex: "username",
      key: "username",
      editable: "true",
    },
    {
      title: "真实姓名",
      dataIndex: "name",
      key: "name",
      editable: "true",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
      editable: "true",
    },
    {
      title: "用户角色",
      dataIndex: "isVIP",
      key: "isVIP",
      editable: "true",
      render: (isVIP: string) => {
        // 判断 membershipStatus 的值
        return isVIP === "1" ? "会员" : "非会员";
      },
    },
    {
      title: "操作",
      key: "action",
      render: (text: string, record: User) => (
        <Space size="middle">
          <Button type="primary" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="删除用户"
            description={`你确定要删除该用户 ${record.username} ?`}
            okText="确定"
            cancelText="取消"
            onConfirm={() => handleDelete(record)}
          >
            <Button type="dashed">删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    reqAdmin(params);
  }, [params]);
  // const pageChange = (page: number, pageSize: number) => {
  //   setParams({ pageNum: page, pageSize: pageSize });
  // };

  //请求角色列表接口方法
  const reqAdmin = async (value: any) => {
    // setLoading(true);
    await reqUserList(value).then((res: any) => {
      res.data.list = res.data.list.map((e: any, index: number) => {
        return {
          ...e,
          key: index,
        };
      });
      // setTotal(res.data.total);
      setData(res.data.list);
      // setLoading(false);
    });
  };
  const [inputValue, setInputValue] = useState<string>("");
  const [selectValue, setSelectValue] = useState<string | undefined>(undefined);
  //搜索功能
  const handleSearch = () => {
    reqAdmin({
      ...params,
      condition: { username: inputValue, isVIP: selectValue },
    });
  };
  //重置功能
  const handleReset = () => {
    setParams({
      ...params,
      condition: { username: "", isVIP: "" },
    });
    setInputValue("");
  };
  //编辑功能
  const handleEdit = (record: User) => {
    console.log(record);

    form.setFieldsValue(record);
    setEditingKey(record.uid);
    setVisible(true);
  };
  //删除功能
  const handleDelete = (record: User) => {
    setData(data.filter((item) => item.uid !== record.uid));
    message.success("删除成功");
  };
  //添加按钮
  const handleAdd = () => {
    form.resetFields();
    setEditingKey("");
    setVisible(true);
  };

  //弹窗取消
  const handleCancel = () => {
    setVisible(false);
  };
  //弹窗完成
  const onFinish = (values: any) => {
    if (editingKey) {
      const index = data.findIndex((item) => item.uid === editingKey);
      if (index !== -1) {
        const newData = [...data];
        newData[index] = { id: index, ...newData[index], ...values };
        setData(newData);
        setEditingKey("");
        setVisible(false);
        message.success("编辑成功");
      }
    } else {
      const newUser = { key: String(Math.random()), ...values };
      setData([...data, newUser]);
      setVisible(false);
      message.success("添加成功");
    }
  };

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          marginBottom: 16,
          padding: "10px 16px 0",
        }}
      >
        <div style={{ display: "flex" }}>
          <Select
            placeholder="是否会员"
            style={{ width: 150, marginRight: "16px" }}
            value={selectValue}
            onChange={(value: string) => setSelectValue(value)}
          >
            <Option value="1">会员</Option>
            <Option value="0">非会员</Option>
          </Select>
          <Input
            placeholder="输入您需要查找的昵称"
            style={{ width: 200, marginRight: "16px" }}
            value={inputValue}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              setInputValue(e.target.value)
            }
          />
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button style={{ marginLeft: "8px" }} onClick={handleReset}>
            重置
          </Button>
        </div>
        <Button type="primary" onClick={handleAdd}>
          添加用户
        </Button>
      </div>
      <Table
        columns={columns}
        rowKey={(record) => record.uid}
        dataSource={data}
        pagination={{ pageSize: 5 }}
        rowSelection={{
          onChange: (selectedRowKeys, selectedRows) => {
            console.log(selectedRowKeys, selectedRows);
          },
        }}
        bordered
      />
      <Modal
        title={editingKey ? "编辑用户" : "添加用户"}
        open={visible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form form={form} onFinish={onFinish}>
          <Form.Item
            label="用户昵称"
            name="username"
            rules={[{ required: true, message: "请输入用户昵称" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="年龄"
            name="age"
            rules={[{ required: true, message: "请输入年龄" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="电话"
            name="phone"
            rules={[{ required: true, message: "请输入地址" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagementPage;
